package com.gserver.commons.resource.impl;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.gserver.commons.resource.IResource;
import com.gserver.commons.resource.IResourceLoader;

public abstract class AbstractResource implements IResourceLoader, IResource {

	public <T> T get(Class<T> clazz) {
		return (T) resources.get(clazz);
	}

	public <T> T get(Object id, Class<T> clazz) {
		return (T) resource.get(id);
	}

	public <T> ImmutableCollection<T> getList(Class<T> clazz) {
		return ImmutableList.copyOf(resource.values());
	}

	public <K, T> ImmutableMap<K, T> getMap(Class<T> clazz) {
		return ImmutableMap.copyOf(resource);
	}

	public <T> List<T> getList(Object id, Class<T> clazz) {
		return (List<T>) resourcs.get(id);
	}

	public <T> ImmutableList<T> getLists(Class<T> clazz) {

		List<T> list = new LinkedList<T>();
		T resourceMarks;
		for (Iterator<T> iterator = resourcs.values().iterator(); iterator
				.hasNext(); list.add(resourceMarks))
			resourceMarks = iterator.next();
		return ImmutableList.copyOf(list);
	}

	public <K, T> Multimap<K, T> getResourcs() {
		return ImmutableMultimap.copyOf(resourcs);
	}

	protected <T> void put(Object id, T mark) {
		if (resource.containsKey(id)) {
			throw new RuntimeException(new StringBuilder(
					" ID\u5FC5\u987B\u552F\u4E00  : ").append(id).toString());
		} else {
			resource.put(id, mark);
			return;
		}
	}

	protected <T> void putList(Object id, T mark) {
		resourcs.put(id, mark);
	}

	public void checkResource() {
	}

	public void check() {
		AbstractResource resource;
		for (Iterator iterator = resources.values().iterator(); iterator
				.hasNext(); resource.checkResource())
			resource = (AbstractResource) iterator.next();
	}

	protected final Map resource = Maps.newLinkedHashMap();
	protected final Multimap resourcs = ArrayListMultimap.create();
	protected static final Map resources = Maps.newHashMap();

}